package com.chorye.mongo.service;

import com.chorye.mongo.entity.Student;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Company: 北京XXXX有限公司
 * @Author JiangYy
 * @Title: StudentService
 * @Description: TODO
 * @Date 2018/12/24 14:32
 */
@Service
public class StudentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存学生
     *
     * @param student
     */
    public Student save(Student student) {
        return mongoTemplate.save(student);
    }

    /**
     * 删除学生
     *
     * @param name
     * @return
     */
    public DeleteResult delete(String name) {
        Query condition = new Query(Criteria.where("name").is(name));
        return mongoTemplate.remove(condition, Student.class);
    }

    /**
     * 修改学生
     *
     * @param student
     * @return
     */
    public UpdateResult update(Student student) {
        Query condition = new Query(Criteria.where("id").is(student.getId()).andOperator(Criteria.where("name").is("mongo")));
        // 更新查询返回结果集的第一条
        Update update = new Update().set("salary", student.getSalary()).set("birth", student.getBirth());
        // 更新查询返回结果集的所有
        // mongoTemplate.updateMulti(condition, update, Student.class);
        return mongoTemplate.updateFirst(condition, update, Student.class);
    }

    /**
     * 查找学生
     *
     * @param name 学生姓名
     * @return
     */
    public Student find(String name) {
        Query condition = new Query(Criteria.where("name").is(name));
        return mongoTemplate.findOne(condition, Student.class);
    }

    /**
     * 查找学生集合
     *
     * @return 学生集合
     */
    public List<Student> findAll() {
        return mongoTemplate.findAll(Student.class);
    }
}
